package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.CustomerLoginDto;
import com.zzyl.dto.MemberDto;
import com.zzyl.entity.Member;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.CustomerLoginService;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import com.zzyl.vo.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @className: CustomerLoginServiceImpl
 * @description:
 * @author: InnovatorX
 * @date: 2024/5/29 11:53
 * @Version: 1.0
 */
@Service
@Slf4j
public class CustomerLoginServiceImpl implements CustomerLoginService {
    @Autowired
    private MemberService memberService;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public LoginVo login(CustomerLoginDto dto) {
        // 调用微信接口,获取OPenID
        String openId = weChatService.getOpenId(dto.getCode());
        log.info("openId:{}", openId);
        // 根据OpenId查询中州的用户数据
        MemberVo memberVo = memberService.findByOpenId(openId);
        // 如果没有数据,创建mapper对象,设置OPenId
        Member member = BeanUtil.toBean(memberVo, Member.class);
        if (member == null) {
            member = new Member();
            member.setOpenId(openId);
        }
        // 调用微信接口,获取手机号
        String phoneNumber = weChatService.getPhoneNumber(dto.getPhoneCode());
        log.info("phoneNumber:{}", phoneNumber);
        // 把手机号设置到用户对象中, 新增,修改用户信息
        if (member.getId() == null){
            member.setPhone(phoneNumber);
            member.setName(phoneNumber.substring(phoneNumber.length() - 4));
            memberService.insert(member);
        }else {
            if (!member.getPhone().equals(phoneNumber)){
                member.setPhone(phoneNumber);
                memberService.update(member);
            }
        }
        // 生成Token, 把用户ID和昵称放入Token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());

        String token = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), claims);

        // 把token放入loginVo,返回给小程序
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }
}
